package com.luban.producer.service.impl;

import com.alibaba.fastjson.JSON;
import com.luban.producer.mapper.TestMapper;
import com.luban.producer.service.TestService;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Map;

/**
 * 需要视频资料或咨询课程的同学可以添加若曦老师的QQ:2746251334
 */
@Service
public class TestServiceImpl implements TestService {

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Autowired
    private TestMapper testMapper;


//    ThreadLocal

//    Map



    @Transactional
    @Override
    public RocketMQLocalTransactionState insert(Message message) {
        System.out.println("执行本地事务");
        Map<String, Object> map = JSON.parseObject(new String((byte[]) message.getPayload()), Map.class);
        RocketMQLocalTransactionState rocketMQLocalTransactionState = testMapper.insert(map) ? RocketMQLocalTransactionState.COMMIT : RocketMQLocalTransactionState.ROLLBACK;
            //map.put(id,结果)

        if (String.valueOf(map.get("id")).equals("100")){
            System.out.println("事务报错");
            int i  = 1/0;
        }else  if(String.valueOf(map.get("id")).equals("101")){
            System.out.println("事务挂起");
            rocketMQLocalTransactionState = RocketMQLocalTransactionState.UNKNOWN;
        }
        return rocketMQLocalTransactionState;
    }

    @Override
    public int checkTransaction(String id) {
        return testMapper.selectCount(id);
    }

    @Override
    public void sendTransactionMessage(Map<String, Object> map) {
        Message message = MessageBuilder.withPayload( JSON.toJSONString(map)).build();
        rocketMQTemplate.sendMessageInTransaction("test",message,null);


    }
}
